#include <iostream>
#include <sys/socket.h>
#include "../socks/sock.h"
#include "../socks/sockdist.h"

using namespace std;

int main(int argc, char** argv)
{
	if(argc > 0)
	{
		bool run = true;
		
		Sock maBR(SOCK_DGRAM, (short)50001, 0);
		
		int descBRLoc;
		char msg[1024];
		
		
		if(maBR.good())
		{
			descBRLoc = maBR.getsDesc();
		}
		else
		{
			cout << "Error : BR" << endl;
			exit(1);
		}
		
		
		cout << "Attente de message ... " << endl;
			
		char tmpRecv[1024];
		int lgRecv = 1024;
		
		SockDist expAppro;
		socklen_t lgAppro = expAppro.getsLen();
		sockaddr_in *adrAppro = expAppro.getAdrDist();
		
		int retourRecv = recvfrom(descBRLoc, tmpRecv, lgRecv, 0, (sockaddr*)adrAppro, &lgAppro);
		
		do
		{
			
			if(retourRecv != -1)
			{
				cout << "Message recu : ";
				cout << tmpRecv << endl;
				
				if(tmpRecv[0] == 'F' && tmpRecv[1] == 'I' && tmpRecv[2] == 'N')
				{
					run = false;
				}
			}
			else
			{
				cout << "Error : retourRecv" << endl;
			}
					
			cout << endl;
			
			if(run)
			{
			
				cout << "Entrer le message à envoyer (FIN pour arreter): ";
				cin.getline(msg, 1024);
			
				cout << "Message envoye : " << msg << endl;
				
				int retourSend = sendto(descBRLoc, msg, sizeof(msg), 0, (sockaddr*)adrAppro, lgAppro);
				
				
				if(msg[0] == 'F' && msg[1] == 'I' && msg[2] == 'N')
				{
					run = false;
				}
			
				if(run)
				{
					if(retourSend == -1)
					{
						cout << "Error : RetourSend" << endl;
					}
					else
					{
						
						int retourRecv = recvfrom(descBRLoc, tmpRecv, lgRecv, 0, (sockaddr*)adrAppro, &lgAppro);
					}
				}
			}
		} while(run);
	}
	
	return 0;
}

 
